package com.hospital.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hospital.domain.pojo.MedicalRecord;
import com.hospital.domain.utils.Result;
import com.hospital.mapper.MedicalRecordMapper;
import com.hospital.service.MedicalRecordService;
import com.hospital.service.ReservationService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class MedicalRecordServiceImpl extends ServiceImpl<MedicalRecordMapper, MedicalRecord> implements MedicalRecordService {

    private final ReservationService reservationService;

    @Override
    public Result record(Integer rId, String result, String info, String advice) {
        System.out.println("接收到的参数 - rId: " + rId + ", result: " + result + ", info: " + info + ", advice: " + advice);
        
        if(rId == null){
            System.out.println("rId为null，返回错误");
            return Result.fail("上传失败：缺少预约ID");
        }
        if(result == null || result.trim().isEmpty() || info == null || info.trim().isEmpty() || advice == null || advice.trim().isEmpty()){
            System.out.println("必填字段为空，返回错误");
            return Result.fail("上传失败：请完整填写诊断结果、病情描述和医嘱");
        }
        
        try {
            System.out.println("=== 开始保存病历 ===");
            System.out.println("输入参数: rId=" + rId + ", result=" + result + ", info=" + info + ", advice=" + advice);
            
            // 首先检查预约ID是否存在
            System.out.println("检查预约ID是否存在: " + rId);
            com.hospital.domain.pojo.Reservation reservation = null;
            try {
                reservation = reservationService.lambdaQuery()
                        .eq(com.hospital.domain.pojo.Reservation::getRId, rId)
                        .one();
                System.out.println("预约查询结果: " + reservation);
            } catch (Exception e) {
                System.out.println("查询预约时发生异常: " + e.getMessage());
                e.printStackTrace();
                return Result.fail("上传失败：查询预约信息时发生异常 - " + e.getMessage());
            }
            
            if (reservation == null) {
                System.out.println("预约ID " + rId + " 不存在于reservation表中");
                return Result.fail("上传失败：预约ID " + rId + " 不存在，请检查预约信息");
            }
            
            System.out.println("找到预约记录: " + reservation);
            
            // 检查是否已经存在该预约ID的病历
            System.out.println("检查是否已存在该预约的病历...");
            MedicalRecord existingRecord = lambdaQuery()
                    .eq(MedicalRecord::getRId, rId)
                    .one();
            if (existingRecord != null) {
                System.out.println("预约ID " + rId + " 的病历已存在: " + existingRecord);
                return Result.fail("上传失败：该预约的病历已存在，无法重复创建");
            }
            
            // 创建病历对象并手动设置字段
            MedicalRecord medicalRecord = new MedicalRecord();
            try {
                medicalRecord.setRId(rId);
                medicalRecord.setMResult(result);
                medicalRecord.setMInfo(info);
                medicalRecord.setMAdvice(advice);
                medicalRecord.setMTime(java.time.LocalDateTime.now());
                System.out.println("病历对象创建成功: " + medicalRecord);
            } catch (Exception e) {
                System.out.println("创建病历对象时发生异常: " + e.getMessage());
                e.printStackTrace();
                return Result.fail("上传失败：创建病历对象时发生异常 - " + e.getMessage());
            }
            
            // 保存病历
            boolean saveResult = false;
            try {
                System.out.println("开始保存病历到数据库...");
                saveResult = save(medicalRecord);
                System.out.println("病历保存结果: " + saveResult + ", rId: " + rId);
            } catch (Exception e) {
                System.out.println("保存病历到数据库时发生异常: " + e.getMessage());
                e.printStackTrace();
                return Result.fail("上传失败：保存病历到数据库时发生异常 - " + e.getMessage());
            }
            
            if (!saveResult) {
                System.out.println("病历保存失败，返回错误");
                return Result.fail("上传失败：病历保存失败");
            }
            
            // 仅更新当前预约的状态为已就诊
            boolean updateResult = false;
            try {
                System.out.println("开始更新预约状态...");
                updateResult = reservationService.lambdaUpdate()
                        .setSql("rState = 1")
                        .eq(com.hospital.domain.pojo.Reservation::getRId, rId)
                        .update();
                System.out.println("预约状态更新结果: " + updateResult);
            } catch (Exception e) {
                System.out.println("更新预约状态时发生异常: " + e.getMessage());
                e.printStackTrace();
                // 这里不返回错误，因为病历已经保存成功了
            }
            
            System.out.println("=== 病历保存完成 ===");
            return Result.ok("上传成功");
        } catch (Exception e) {
            System.out.println("保存病历时发生未捕获的异常: " + e.getMessage());
            System.out.println("异常类型: " + e.getClass().getSimpleName());
            e.printStackTrace();
            return Result.fail("上传失败：系统异常，请联系管理员 - " + e.getMessage());
        }
    }

    @Override
    public Result queryAllMedicalRecords() {
        try {
            System.out.println("开始查询所有病历信息...");
            List<Map<String, Object>> medicalRecords = baseMapper.queryAllMedicalRecordsWithInfo();
            System.out.println("查询到病历数量: " + (medicalRecords != null ? medicalRecords.size() : 0));
            if (medicalRecords != null && medicalRecords.size() > 0) {
                System.out.println("第一条病历数据: " + medicalRecords.get(0));
            }
            return Result.ok(medicalRecords);
        } catch (Exception e) {
            System.out.println("查询病历信息时发生异常: " + e.getMessage());
            e.printStackTrace();
            return Result.fail("查询病历信息失败: " + e.getMessage());
        }
    }

    @Override
    public Result queryMedicalRecordsByDoctor(Integer dId) {
        try {
            if (dId == null) return Result.fail("缺少医生ID");
            List<Map<String, Object>> list = baseMapper.queryMedicalRecordsByDoctor(dId);
            return Result.ok(list);
        } catch (Exception e) {
            return Result.fail("按医生查询病历失败: " + e.getMessage());
        }
    }
}
